package com.ccteam.admin.viewmodels.album

import androidx.lifecycle.*
import com.ccteam.admin.repositories.MusicAdminRepository
import com.ccteam.admin.utils.ErrorMessage
import com.ccteam.admin.utils.LoadMessage
import com.ccteam.admin.utils.setValueIfNew
import com.ccteam.admin.vo.Resource
import com.ccteam.model.music.MusicDetailVO
import com.ccteam.model.music.MusicVO
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/3
 */
@HiltViewModel
class AlbumMusicHomeViewModel @Inject constructor(
    private val musicRepository: MusicAdminRepository,
    savedStateHandle: SavedStateHandle
): ViewModel() {

    private val albumMusicResult = MutableLiveData<Resource<List<MusicDetailVO>>>(Resource.Loading())

    private val _albumMusicList = MediatorLiveData<List<MusicDetailVO>>()
    val albumMusicList get() = _albumMusicList

    val loadMessage: LiveData<LoadMessage> = albumMusicResult.map { result ->
        if (result is Resource.Error) {
            LoadMessage.Error(ErrorMessage(ErrorMessage.ERROR_SNACK_TYPE, result.message))
        } else if(result is Resource.Loading) {
            LoadMessage.Loading
        } else {
            if(result.data.isNullOrEmpty()){
                LoadMessage.Empty
            } else {
                LoadMessage.NotLoading
            }
        }
    }

    private val albumId = MutableLiveData<String>()

    init {
        _albumMusicList.addSource(albumId){
            refreshAlbumMusic()
        }

        _albumMusicList.addSource(albumMusicResult){
            albumMusicList.value = it.data ?: emptyList()
        }

        albumId.setValueIfNew(savedStateHandle["albumId"])

    }

    fun refreshAlbumMusic(){
        viewModelScope.launch {
            albumId.value?.let {
                val musicList = musicRepository.getAlbumMusicList(it)
                albumMusicResult.value = musicList
            }
        }
    }

}